import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'

export const createVitePlugin = () => {
  const vitePlugin = [
    vue(),
    vueJsx(),
    AutoImport({
      // 目标文件
      include: [
        /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
        /\.vue$/,
        /\.vue\?vue/, // .vue
        /\.md$/ // .md
      ],
      // 自动导入 Vue 相关函数，如：ref, reactive, toRef 等
      imports: ['vue', 'vue-router'],
      // Generate corresponding .eslintrc-auto-import.json file.
      // eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals
      eslintrc: {
        enabled: false, // Default `false`
        filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
        globalsPropValue: true // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
      },
      // 声明文件生成位置和文件名称
      dts: './auto-imports.d.ts'
    }),
    Components({})
  ]
  return vitePlugin
}
export const createViteProxy = () => {
  return {
    '/api': {
      target: 'http://123.207.32.32:9060/beike/api',
      changeOrigin: true,
      ws: true,
      rewrite: (path: string) => path.replace(new RegExp(`^\/api`), ''),
      secure: false,
      bypass: (req, res, options) => {
        /**
         * @description URL(url,base)是一个表示绝对或者相对URL的DOMString
         * @description 如果url是相对URL,则会将base作为基准URL
         * @description 如果url是绝对URL,则无论参数base是否存在，都将被忽略
         */
        const proxyUrl = new URL(options?.rewrite(req?.url) || '', options.target as string)?.href || '';
        console.log('proxyUrl', proxyUrl);
        req.headers['x-req-proxyUrl'] = proxyUrl; //设置请求头无效
        res.setHeader('x-req-proxyUrl', proxyUrl); //设置响应头有效
      },
    }
  }
}
